<template>
  <div class="container">
    <div class="form-warp">
      <form class="sign-in-form">
        <h2 class="form-title">登录</h2>
        <div id="Form">
          <el-form
              ref="loginFormRef"
              :model="loginForm"
              :rules="rulesLogin"
              class="ruleForm"
              label-position="right"
              status-icon
          >
            <el-form-item prop="name" style="width: 100%">
              <el-input v-model="loginForm.name" autocomplete="off" placeholder="用户名" type="text"/>
            </el-form-item>
            <el-form-item prop="pass" style="width: 100%">
              <el-input v-model="loginForm.pass" autocomplete="off" placeholder="密码" type="password"/>
            </el-form-item>

          </el-form>
        </div>
        <input class="submit-btn" type="button" value="立即登录" @click="submitForm(loginFormRef)"/>
      </form>
      <form class="sign-up-form">
        <h2 class="form-title">注册</h2>
        <div id="Form">
          <el-form
              ref="registerFormRef"
              :model="registerForm"
              :rules="rules"
              class="ruleForm"
              label-position="right"
              status-icon
          >
            <el-form-item prop="account" style="width: 100%">
              <el-input v-model="registerForm.account" autocomplete="off" placeholder="账户"
                        type="text"/>
            </el-form-item>
            <el-form-item prop="pass" style="width: 100%">
              <el-input v-model="registerForm.pass" autocomplete="off" placeholder="密码" type="password"/>
            </el-form-item>
            <el-form-item prop="checkPass" style="width: 100%">
              <el-input v-model="registerForm.checkPass" autocomplete="off" placeholder="确认密码" type="password"/>
            </el-form-item>
            <el-form-item prop="name" style="width: 100%">
              <el-input v-model="registerForm.name" autocomplete="off" placeholder="姓名" type="text"/>
            </el-form-item>
            <el-form-item prop="position" style="width: 100%">
              <el-select
                  v-model="registerForm.position"
                  class="selecting"
                  placeholder="职位"
              >
                <el-option
                    v-for="item in optionPositions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <input class="submit-btn" type="button" value="立即注册" @click="register(registerFormRef)"/>
      </form>
    </div>
    <div class="desc-warp">
      <div class="desc-warp-item sign-up-desc">
        <div class="content">
          <button id="sign-up-btn">注册</button>
        </div>
        <img alt="" src="http://101.35.94.229:888/images/svg/log.png">
      </div>
      <div class="desc-warp-item sign-in-desc">
        <div class="content">
          <button id="sign-in-btn">登录</button>
        </div>
        <img alt="" src="http://101.35.94.229:888/images/svg/registerCapge.png">
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>

import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from 'element-plus'
import {ElMessage} from 'element-plus'
import router from '@/router'
import {useUserInfoStore} from '@/stores/User/UserInfo'
import {useIsAdmin} from '@/stores/Person/IsAdmin'
import {getUserInfoApi, registerApi} from '@/api/User'
import {useRegisterStore} from '@/stores/registerUser'
import {usePositionStore} from '@/stores/Person/Position'

onMounted(function start() {
  document.addEventListener('keydown', handleWatchEnter)
  const singUpBtn = document.querySelector('#sign-up-btn')
  const singInBtn = document.querySelector('#sign-in-btn')
  const container = document.querySelector('.container')

  singUpBtn.addEventListener('click', () => {
    container.classList.add('sign-up-mode')
  })
  singInBtn.addEventListener('click', () => {
    container.classList.remove('sign-up-mode')
  })
})


const PositionStore = usePositionStore()
const isAdmin = useIsAdmin()
const userInfoStore = useUserInfoStore()
const registerStore = useRegisterStore()

// 绑定回车按键
const handleWatchEnter = (e) => {
  const key = window.event ? e.keyCode : e.which;
  const container = document.querySelector('.container')
  if (key === 13 && !container.classList.contains('sign-up-mode')) {
    // 这里执行相应的行为动作
    submitForm(loginFormRef.value)
  } else if (key === 13 && container.classList.contains('sign-up-mode')) {
    register(registerFormRef.value)
  }
}
// 注册失败弹窗
const registerError = (message) => {
  ElMessage({
    message: message,
    type: 'error'
  })
}
// 注册axios请求
const register = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      registerStore.registerUser(registerForm.account, registerForm.pass, registerForm.name, registerForm.position)
      registerApi(registerStore.useraccount, registerStore.password, registerStore.password, registerStore.username, registerStore.position)
          .then(function (res) {
            console.log(res)
            if (res['code'] == 200) {
              const container = document.querySelector('.container')
              container.classList.remove('sign-up-mode')
              console.log('注册成功')
            } else {
              registerError('注册失败,原因是:' + res["data"])
              console.log('注册失败')
            }
          })
    } else {
      console.log('error submit!', fields)
    }
  })
}


const info = reactive({
  info: '',
  isStatus: '',
  isname: 0,
  ispass: 0
})
const registerFormRef = ref<FormInstance>()

// 检查输入
const checkRegisterName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入姓名'))
  } else {
    callback()
  }
}
const checkAccount = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户名'))
  } else {
    callback()
  }
}
const checkPosition = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请选择职位'))
  } else {
    callback()
  }
}
const checkRegisterPass = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
const checkSamePass = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请再次输入密码'))
  } else if (value != registerForm.pass) {
    return callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}

const registerForm = reactive({
  account: '',
  name: '',
  pass: '',
  checkPass: '',
  position: ''
})

const rules = reactive({
  account: [{required: true, validator: checkAccount, trigger: 'blur'}],
  name: [{required: true, validator: checkRegisterName, trigger: 'blur'}],
  pass: [{required: true, validator: checkRegisterPass, trigger: 'blur'}],
  checkPass: [{required: true, validator: checkSamePass, trigger: 'blur'}],
  position: [{required: true, validator: checkPosition, trigger: 'blur'}]
})

const optionPositions = PositionStore.positions


const loginFormRef = ref<FormInstance>()
const checkName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入姓名'))
  } else {
    callback()
  }
}
const checkPass = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
const login = (username: string, password: string) => {
  userInfoStore.loginUser(username, password)
}
const loginForm = reactive({
  name: '',
  pass: ''
})

const rulesLogin = reactive({
  name: [{validator: checkName, trigger: 'blur'}],
  pass: [{validator: checkPass, trigger: 'blur'}]
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      getUserInfoApi(loginForm.name, loginForm.pass).then(response => {
        if (response['code'] == 200) {
          if (response["data"]['userAccount'] != null) {
            userInfoStore.$patch({
              departmentId: response["data"].departmentId,
              isDelete: response["data"].isDelete,
              isRole: response["data"].isRole,
              levelId: response["data"].levelId,
              positionId: response["data"].positionId,
              projectId: response["data"].projectId,
              statusId: response["data"].statusId,
              userAccount: response["data"].userAccount,
              userAvatarUrl: response["data"].userAvatarUrl,
              userCreateTime: response["data"].userCreateTime,
              userEmail: response["data"].userEmail,
              userEntryTime: response["data"].userEntryTime,
              userGender: response["data"].userGender,
              userId: response["data"].userId,
              userName: response["data"].userName,
              userPassword: response["data"].userPassword,
              userPhone: response["data"].userPhone,
              userUpdateTime: response["data"].userUpdateTime
            })
            login(loginForm.name, loginForm.pass)
            isAdmin.checkAdmin(response["data"].isRole)
            router.push('/home')
          }
        } else {
          alert(response['data'])
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


</script>

<style lang="scss" scoped>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  color: #333;
}


.container {
  position: relative;
  min-height: 100vh;
  width: 100%;
  overflow: hidden;
}

.container::before {
  content: " ";
  position: absolute;
  width: 2000px;
  height: 2000px;
  border-radius: 50%;
  background-image: linear-gradient(-45deg, #6266f5 0%, #04befe 100%);
  transition: 1.8s ease-in-out;
  z-index: 6;
  top: -10%;
  right: 48%;
  transform: translateY(-50%);
}

.container.sign-up-mode::before {
  transform: translate(100%, -50%);
}

.form-warp {
  width: 50%;
  position: absolute;
  z-index: 5;
  left: 75%;
  top: 50%;
  z-index: 5;
  transform: translate(-50%, -50%);
  display: grid;
  grid-template-columns: 1fr;
  transition: 1s 0.7s ease-in-out;
}

.form-warp form {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 20px;
  /* 将两个 form 布局在 grid 同一位置 */
  grid-row: 1 / 2;
  grid-column: 1 / 2;
  transition: all 0.2s 0.7s;
  opacity: 1;
  z-index: 4;
}

.form-title {
  color: #6266f5;
}

.form-warp .sign-up-form {
  opacity: 0;
  z-index: 3;
}

.container.sign-up-mode .form-warp {
  left: 25%;
}

.container.sign-up-mode .sign-in-form {
  opacity: 0;
  z-index: 3;
}

.container.sign-up-mode .sign-up-form {
  opacity: 1;
  z-index: 4;
}

.submit-btn {
  min-width: 300px;
  outline: none;
  padding: 12px 30px;
  line-height: 1;
  font-size: 16px;
  border-radius: 60px;
  color: #333;
  background-color: #6267f513;
  border: none;
}


.submit-btn {
  background-color: #6266f5;
  color: #FFF;
  text-align: center;
  min-width: 150px;
  font-size: initial;
  font-weight: bold;
  letter-spacing: 1.5px;
  cursor: pointer;
}

.desc-warp {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.desc-warp-item {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-around;
  text-align: center;
  text-align: center;
  padding: 3rem 17% 2rem 12%;
  z-index: 6;
}

/* 事件穿透 BEGIN */
.sign-in-desc {
  pointer-events: none;
}

.sign-up-mode .sign-in-desc {
  pointer-events: all;
}

.sign-up-mode .sign-up-desc {
  pointer-events: none;
}

/* 事件穿透 END */
.content {
  width: 100%;
  transition: transform 0.9s ease-in-out;
  transition-delay: .6s;
}

.sign-in-desc img,
.sign-in-desc .content {
  transform: translateX(800px);
}

.sign-up-mode .sign-in-desc img,
.sign-up-mode .sign-in-desc .content {
  transform: translateX(0);
}

.sign-up-mode .sign-up-desc img,
.sign-up-mode .sign-up-desc .content {
  transform: translateX(-800px);
}

button {
  outline: none;
  padding: 6px 8px;
  min-width: 100px;
  text-align: center;
  border-radius: 30px;
  border: 2px solid #FFF;
  background: none;
  color: #FFF;
  cursor: pointer;
  transition: all .3s ease;
}

button:active {
  background: rgba(255, 255, 255, .1);
}

img {
  width: 100%;
  display: block;
  transition: transform 0.9s ease-in-out;
  transition-delay: .5s;
}

/* 响应式 */
@media screen and (max-width: 870px) {
  .container::before {
    width: 1500px;
    height: 1500px;
    transform: translateX(-50%);
    left: 30%;
    bottom: 68%;
    right: initial;
    top: initial;
    transition: 2s ease-in-out;
  }

  .container.sign-up-mode::before {
    transform: translate(-50%, 100%);
    bottom: 20%;
    right: initial;
  }

  .form-warp {
    width: 100%;
    top: 75%;
    left: 50%;
    transform: translate(-50%, -100%);
    transition: 1s 0.8s ease-in-out;
  }

  .container.sign-up-mode .form-warp {
    top: 25%;
    left: 50%;
    transform: translate(-50%, 0);
  }

  img {
    width: 200px;
    transition: transform 0.9s ease-in-out;
    transition-delay: 0.7s;
  }

  .desc-warp {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr 2fr 1fr;
  }

  .desc-warp-item {
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    padding: 2.5rem 8%;
    grid-column: 1 / 2;
  }

  .sign-in-desc {
    grid-row: 3 / 4;
  }

  .sign-in-desc img,
  .sign-in-desc .content {
    transform: translateY(800px);
  }

  .sign-up-mode .sign-in-desc img,
  .sign-up-mode .sign-in-desc .content {
    transform: translateY(0);
  }

  .sign-up-mode .sign-up-desc img,
  .sign-up-mode .sign-up-desc .content {
    transform: translateY(-800px);
  }
}

@media screen and (max-width: 570px) {
  .container::before {
    bottom: 72%;
    left: 50%;
  }

  img {
    display: none;
  }
}
</style>